package com.kgc.warehouse.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.kgc.warehouse.system.Utils.TreeUtil;
import com.kgc.warehouse.system.common.CodeMsg;
import com.kgc.warehouse.system.common.ResponseResult;
import com.kgc.warehouse.system.dto.PwdDto;
import com.kgc.warehouse.system.dto.UserPageDto;
import com.kgc.warehouse.system.entity.*;
import com.kgc.warehouse.system.mapper.*;

import com.kgc.warehouse.system.service.UserService;
import com.kgc.warehouse.system.vo.PermissionVO;
import com.kgc.warehouse.system.vo.UserVo;
import com.mysql.cj.util.StringUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author main
 * @description 针对表【sys_user】的数据库操作Service实现
 * @createDate 2023-02-03 20:07:42
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private DeptMapper deptMapper;
    @Autowired(required = false)
    private UserRoleMapper userRoleMapper;
    @Autowired(required = false)
    private RoleMapper roleMapper;

    @Autowired(required = false)
    private RolePermissionMapper rolePermissionMapper;
    @Autowired(required = false)
    private PermissionMapper permissionMapper;

    @Override
    public ResponseResult selectPage(UserPageDto userPageDto) {
        Page<User> userPage = new Page<>(userPageDto.getPage(), userPageDto.getLimit());

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();

        userLambdaQueryWrapper.like(!StringUtils.isNullOrEmpty(userPageDto.getName()),User::getName, userPageDto.getName())
                .like(!StringUtils.isNullOrEmpty(userPageDto.getAddress()),User::getAddress, userPageDto.getAddress());

        userMapper.selectPage(userPage, userLambdaQueryWrapper);

        //获取分页数据
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();

        List<User> collect = records.stream().map(user -> {

            if (user.getDeptid() != null) {
                Dept dept = deptMapper.selectById(user.getDeptid());
                String deptName = dept.getName();
                user.setDeptname(deptName);
            }
            if (user.getMgr() != null && user.getMgr() != 0) {
                User mgr = userMapper.selectById(user.getMgr());
                user.setLeadername(mgr.getName());
            }

            //根据用户id查询角色信息
            // 获取用户id  查询角色信息
            Integer id = user.getId();
            LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userRoleLambdaQueryWrapper.eq(UserRole::getUid,id);
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleLambdaQueryWrapper);

            //遍历集合 获取角色id  user_role

            List<Integer> roleIds = userRoles.stream().map(userRole -> {
                return userRole.getRid();
            }).collect(Collectors.toList());
            // 根据角色id 查询角色信息  role

            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.in("id",roleIds);
            List<Role> roles = roleMapper.selectList(roleQueryWrapper);

            // 遍历角色集合 获取角色名字
            List<String> roleNames = roles.stream().map(role -> {
                return role.getName();
            }).collect(Collectors.toList());
            user.setRoles(roleNames);

            return user;

        }).collect(Collectors.toList());
        return new ResponseResult(collect,total, CodeMsg.SUCCESS);
    }

    @Override
    public ResponseResult addUser(UserVo userVo) {
        //查询账户是否存在
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getLoginname,userVo.getLoginname());
        User user1 = userMapper.selectOne(userLambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(user1))
        {
            return new ResponseResult(CodeMsg.USERNAME_EXIST);
        }else{
            //插入新用户

            User user = new User();
            BeanUtils.copyProperties(userVo,user);
            //设置盐
            String salt = IdUtil.simpleUUID().toUpperCase();
            userVo.setSalt(salt);
            String md5pwd = new Md5Hash("123456", salt, 2).toHex();
            user.setSalt(salt);
            user.setPwd(md5pwd);
            userMapper.insert(user);
            //更新用户角色表
            List<Integer> roleIds = userVo.getRoleIds();
            Integer usrId = user.getId();
            roleIds.forEach(roleId->{

                UserRole userRole = new UserRole();
                userRole.setUid(usrId);
                userRole.setRid(roleId);
                userRoleMapper.insert(userRole);
            });

        }
        return new ResponseResult(CodeMsg.SUCCESS);
    }

    @Override
    public ResponseResult getUserById(Integer id) {
        User user = userMapper.selectById(id);
        log.info("======="+user);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);

        //根据id查询角色表
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.in(UserRole::getUid,id);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleLambdaQueryWrapper);
        List<Integer> roleIds = userRoles.stream().map(userRole -> {
            return userRole.getRid();
        }).collect(Collectors.toList());
        List<Role> roles = roleIds.stream().map(roleId -> {
            return roleMapper.selectById(roleId);
        }).collect(Collectors.toList());
        userVo.setRoleIds(roleIds);
        return new ResponseResult(userVo,null,CodeMsg.SUCCESS);
    }

    @Override
    public ResponseResult deletebyId(String ids) {

        String[] split = ids.split(",");

        ArrayList<Integer> integers = new ArrayList<>();
        for (String s : split) {
            integers.add(Integer.valueOf(s));
        }
        //删除用户信息
        userMapper.deleteBatchIds(integers);
        //删除用户角色信息
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.in(UserRole::getUid,integers);
        userRoleMapper.delete(userRoleLambdaQueryWrapper);
        return new ResponseResult(CodeMsg.SUCCESS);
    }

    @Override
    public ResponseResult updateUser(UserVo userVo) {
        //插入新用户
        User user = new User();
        BeanUtils.copyProperties(userVo,user);
        userMapper.updateById(user);
        //更新用户角色表
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.in(UserRole::getUid,userVo.getId());
        userRoleMapper.delete(userRoleLambdaQueryWrapper);
        List<Integer> roleIds = userVo.getRoleIds();
        Integer usrId = user.getId();
        roleIds.forEach(roleId->{

            UserRole userRole = new UserRole();
            userRole.setUid(usrId);
            userRole.setRid(roleId);
            userRoleMapper.insert(userRole);
        });
        return new ResponseResult(CodeMsg.SUCCESS);
    }

    @Override
    public Map<String, Object> menu(String username) {
        HashMap<String, Object> map = new HashMap<>(16);
        HashMap<String, Object> home = new HashMap<>(16);
        HashMap<String, Object> logo = new HashMap<>(16);

        //初始化home、log
        //首页信息初始化
        home.put("title","首页");
        home.put("href","https://www.8zt.cc");
        map.put("homeInfo",home);
        //logo信息初始化

        logo.put("title","进销存管理系统");
        logo.put("image","images/logo.png");
        logo.put("href","www.baidu.com");
        map.put("logoInfo",logo);

        //设置菜单信息

        //根据用户名查询用户id
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getLoginname,username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);

        //根据用户id查询用户角色id
        Integer id = user.getId();
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(UserRole::getUid,id);
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleLambdaQueryWrapper);
        List<Integer> roleIds = userRoles.stream().map(userRole -> {
            return userRole.getRid();
        }).collect(Collectors.toList());

        //根据角色id查询角色权限关联表
        LambdaQueryWrapper<RolePermission> rolePermissionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        rolePermissionLambdaQueryWrapper.in(RolePermission::getRid,roleIds);
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(rolePermissionLambdaQueryWrapper);
        List<Integer> persIds = rolePermissions.stream().map(rolePermission -> {
            return rolePermission.getPid();
        }).collect(Collectors.toList());


        //根据权限id查询权限

        List<Permission> permissions = permissionMapper.selectBatchIds(persIds);

        List<PermissionVO> permissionVOS = permissions.stream().map(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);

            return permissionVO;
        }).filter(p -> !p.getType().equals("permission")).collect(Collectors.toList());

        List<PermissionVO> permissionVOSList = TreeUtil.toTree(permissionVOS, 0);
        map.put("menuInfo",permissionVOSList);

        return map;
    }

    @Override
    public ResponseResult updateAvailable(Integer id, Integer available) {

        userMapper.updateAvailable(id,available);
        return new ResponseResult(CodeMsg.SUCCESS);
    }

    @Override
    public ResponseResult resetPwd(Integer id) {

        //设置盐
        String salt = IdUtil.simpleUUID().toUpperCase();
        String md5pwd = new Md5Hash("123456", salt, 2).toHex();

        userMapper.resetPwd(id,md5pwd,salt);
        return new ResponseResult(CodeMsg.RESET_PWD);
    }

    @Override
    public Integer changePwd(User user, PwdDto pwdDto) {

        String oldPwd = new Md5Hash(pwdDto.getOld_password(), user.getSalt(), 2).toHex();
        if (!oldPwd.equals(user.getPwd()))
        {
            return 1;
        }
        if (!pwdDto.getAgain_password().equals(pwdDto.getNew_password()))
        {
            return 2;
        }
        String salt = IdUtil.simpleUUID().toUpperCase();
        String md5pwd = new Md5Hash(pwdDto.getNew_password(), salt, 2).toHex();
        userMapper.resetPwd(user.getId(),md5pwd,salt);

        return 0;
    }
}




